<?php
session_start();
header("Content-type: image/PNG");

//定义画布的宽和高
$width = 60;
$height = 25;

//生成验证码并保存到Session
$captcha_num = '';
for ($i = 0; $i < 4; ++$i) {
    $captcha_num .= rand(0, 9);
}
$_SESSION['captcha'] = $captcha_num;

//创建画布
$img = imagecreate($width, $height);

//设置画布颜色
$bg_color = imagecolorallocate($img, 255, 255, 255);

//生成干扰线
for ($i = 0; $i < 5; ++$i) {
    $line_color = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
    imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
}

//生成干扰点
for ($i = 0; $i < 100; ++$i) {
    $pixel_color = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
    imagesetpixel($img, rand(0, $width), rand(0, $height), $pixel_color);
}

//设置验证码颜色和大小
$captcha_color = imagecolorallocate($img, 0, 0, 0);
$captcha_size = 20;

//将验证码画到画布上
imagestring($img, $captcha_size, 10, 5, $captcha_num, $captcha_color);

//输出画布
imagepng($img);

//释放资源
imagedestroy($img);
?>